import subprocess
import tempfile
import os
import time
from pathlib import Path
from typing import Tuple

class CodeExecutor:
    def __init__(self, timeout: int = 5, memory_limit: int = 128):
        self.timeout = timeout  # 执行超时时间（秒）
        self.memory_limit = memory_limit  # 内存限制（MB）

    def execute_python_file(self, file_path: str) -> Tuple[str, str]:
        """
        执行Python代码文件并返回执行结果
        
        参数:
            file_path: Python代码文件路径
            
        返回:
            (output, error): 执行输出和错误信息
        """
        if not os.path.exists(file_path):
            return "", f"File not found: {file_path}"
            
        try:
            # 使用subprocess在受限环境中执行
            result = subprocess.run(
                ["python", file_path],
                capture_output=True,
                text=True,
                timeout=self.timeout,
                env=self._get_safe_env(),
            )
            return result.stdout, result.stderr
        except subprocess.TimeoutExpired:
            return "", f"Execution timed out after {self.timeout} seconds"
        except Exception as e:
            return "", str(e)

    def _get_safe_env(self) -> dict:
        """获取安全的环境变量配置"""
        env = os.environ.copy()
        # 限制内存使用
        env["PYTHONMALLOC"] = "malloc"
        env["PYTHONMALLOCSTATS"] = "1"
        return env

def execute_code(file_path: str) -> dict:
    """
    执行Python代码并返回格式化结果
    
    参数:
        file_path: Python代码文件路径
        
    返回:
        {
            "success": bool,  # 是否执行成功
            "output": str,    # 标准输出
            "error": str,     # 错误信息
            "timestamp": str  # 执行时间
        }
    """
    executor = CodeExecutor()
    output, error = executor.execute_python_file(file_path)
    
    return {
        "success": not bool(error),
        "output": output,
        "error": error,
        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
    }

if __name__ == "__main__":
    """测试正常代码执行"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write("print('Hello World')")
        test_file = f.name

    result = execute_code(test_file)
    print(result["success"])
    print(result["output"])
    print(result["error"])

    # 测试错误代码
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write("1/0")
        test_file = f.name

    result = execute_code(test_file)
    print(result["success"])
    print(result["error"])

    # 测试文件不存在
    result = execute_code("non_existent_file.py")
    print(result["success"])
    print(result["error"])
    """测试执行超时"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write("import time\ntime.sleep(10)")
        test_file = f.name

    result = execute_code(test_file)
    print(result["success"])
    print(result["error"])

